package com.train.sentinel.controllers;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.train.sentinel.feigns.PayServer;
import com.train.sentinel.sentinelHandler.FallbackConfig;
import com.train.sentinel.sentinelHandler.HandlerConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
public class SentinelController {
    @Autowired
    PayServer payServer;
    @Value("${server.port}")
    int port;

    @GetMapping(path = {"/testA"})
    public Map testA(){
        Map result = new HashMap<String,Object>();
        result.put("sentinel_server","A");
        return result;
    }
    @GetMapping(path = {"/testB"})
    public Map testB(){
        Map result = new HashMap<String,Object>();
        result.put("sentinel_server","B");
        return result;
    }
    @GetMapping(path = {"/testC"})
    @SentinelResource(value = "test_c",blockHandler = "testChandler")
    public Map testC(@RequestParam(value = "p1") String p1,
                     @RequestParam(value = "p2") String p2){
        Map result = new HashMap<String,Object>();
        log.warn(p1+" "+p2);
        result.put("p1",p1);
        result.put("p2",p2);
        return result;
    }
    public Map testChandler(String p1,String p2,BlockException blockException){
        Map result = new HashMap<String,Object>();
        log.warn("testChandler:"+p1+" "+p2);
        result.put("sentinel_server","error");
        return result;
    }
    /**
     * 服务降级集中化配置测试
     * */
    @GetMapping(path = {"/testD"})
    @SentinelResource(value = "test_d",
            blockHandlerClass = HandlerConfig.class,blockHandler = "errorMsg",
            fallbackClass = FallbackConfig.class, fallback="fallback",
            exceptionsToIgnore = {IllegalArgumentException.class}
    )
    public Map testD(@RequestParam("p1") String p1){
        if ( p1.equals("admin")){
            throw new IllegalArgumentException("非法参数异常-admin不能用于申请");
        } else if ( p1.isEmpty() ) {
            throw new NullPointerException("p1不能为空");
        }
        Map result = new HashMap<String,Object>();
        result.put("sentinel_server","testD");
        result.put("p1",p1);
        result.put("port",port);
        return result;
    }
    @GetMapping(path = {"/pay"})
    public String invokeOpenFeign(){
        return payServer.sentinel();
    }
}